package com.booksystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.booksystem.common.RestResult;
import com.booksystem.dto.*;
import com.booksystem.dto.InventoryQueryDTO;
import com.booksystem.dto.ManualAdjustmentDTO;
import com.booksystem.dto.StockInfoDTO;
import com.booksystem.dto.WarningThresholdUpdateDTO;
import com.booksystem.entity.InventoryLogDO;
import com.booksystem.entity.ProductInfoDO;
import com.booksystem.exception.BusinessException;
import com.booksystem.mapper.InventoryLogMapper;
import com.booksystem.mapper.ProductInfoMapper;
import com.booksystem.service.InventoryService;
import com.booksystem.utils.ResultCodeConstant;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   库存管理服务实现类
 * </p>
 * @author 段伟豪
 */
@Slf4j
@Service
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private InventoryLogMapper inventoryLogMapper;

    @Override
    public RestResult<StockInfoDTO> getStock(InventoryQueryDTO queryDTO) {
        // 根据商品ID查询商品信息
        QueryWrapper<ProductInfoDO> wrapper = new QueryWrapper<>();
        wrapper.select("stock_quantity").eq("product_id", queryDTO.getProductId());
        ProductInfoDO productInfo = productInfoMapper.selectOne(wrapper);
        
        if (productInfo == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, null);
        }
        
        StockInfoDTO stockInfo = new StockInfoDTO();
        stockInfo.setStockQuantity(productInfo.getStockQuantity());
        
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, stockInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> setWarningThreshold(WarningThresholdUpdateDTO updateDTO) {
        // 验证商品是否存在
        QueryWrapper<ProductInfoDO> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", updateDTO.getProductId());
        ProductInfoDO productInfo = productInfoMapper.selectOne(wrapper);
        
        if (productInfo == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, false);
        }
        
        // 更新商品的库存预警阈值
        productInfo.setStockQuantity(updateDTO.getWarningThreshold());
        int rowsAffected = productInfoMapper.updateById(productInfo);
        
        if (rowsAffected <= 0) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> adjustStock(ManualAdjustmentDTO adjustmentDTO) {
        // 验证商品是否存在
        QueryWrapper<ProductInfoDO> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", adjustmentDTO.getProductId());
        ProductInfoDO productInfo = productInfoMapper.selectOne(wrapper);
        
        if (productInfo == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, false);
        }
        
        // 检查库存变更后的值是否小于0
        Integer newStock = productInfo.getStockQuantity() + adjustmentDTO.getQuantityChange();
        if (newStock < 0) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "库存不足或不能为负数", false);
        }
        
        // 执行库存调整
        productInfo.setStockQuantity(newStock);
        int rowsAffected = productInfoMapper.updateById(productInfo);
        
        if (rowsAffected <= 0) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        
        // 记录日志
        InventoryLogDO logEntry = new InventoryLogDO();
        logEntry.setProductId(adjustmentDTO.getProductId());
        logEntry.setChangeType(3); // 调整类型
        logEntry.setQuantityChange(adjustmentDTO.getQuantityChange());
        logEntry.setCurrentStock(newStock);
        logEntry.setOperator(adjustmentDTO.getOperator());
        logEntry.setRemark(adjustmentDTO.getRemark());
        logEntry.setCreateBy(logEntry.getOperator()); // 简化处理，默认创建人为操作人
        logEntry.setCreateTime(new Date());
        inventoryLogMapper.insert(logEntry);
        
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, true);
    }
}